package com.itheima.mp.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.emuns.UserStaus;
import com.itheima.mp.entity.Address;
import com.itheima.mp.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public void reductionUserById(Long id, Float amount) {
        User user = this.getById(id);
        Float remainBalance = user.getBalance() - amount;
        if (user.getId() == null || user.getStatus() == UserStaus.FROZEN) {
            new RuntimeException("用户状态异常");
        } else if (user.getId() == null || remainBalance < 0) {
            new RuntimeException("扣除失败，用户为空或者余额不足");
        } else
            lambdaUpdate().set(User::getBalance, remainBalance).set(remainBalance == 0, User::getStatus, UserStaus.FROZEN).eq(User::getId, id).eq(User::getBalance, user.getBalance()).update();
    }

    @Override
    public UserVO getUserInfoAndAddressInfo(Long id) {
        User user = getById(id);
        UserVO uservo = BeanUtil.copyProperties(user, UserVO.class);
        if (user.getId() == null) {
            new RuntimeException("用户表里没有这个用户");
        }
        List<Address> addresslist = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        uservo.setAddress(BeanUtil.copyToList(addresslist, AddressVO.class));
        return uservo;
    }

    @Override
    public List<UserVO> queryListUser(List<Long> ids) {
        //1.批量查询用户(po)
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            log.info("查询无结果");
            return Collections.emptyList();
        }
        //2.批量查询用户的地址
        //2.1 获取用户的id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //2.2 根据用户id查询地址
        List<Address> addressList = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        //2.3 地址转VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(addressList, AddressVO.class);
        //2.4用户地址集合分组处理，相同用户放在一个集合（组）中
        Map<Long, List<AddressVO>> addressMap = new HashMap<>();
        if (CollUtil.isNotEmpty(addressVOS)) {
            addressMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        //3.批量把po封装成vo,最终为UserVO
        List<UserVO> userVO = new ArrayList<>(users.size());
        for (User user : users) {
            //3.1 把user的po转换vo
            UserVO uservo = BeanUtil.copyProperties(user, UserVO.class);
            userVO.add(uservo);
            //3.2转换地址vo
            uservo.setAddress(addressMap.get(user.getId()));
        }
        return userVO;
    }

    @Override
    public PageDTO<UserVO> getFixUserQuery(UserQuery userQuery) {
        log.info(userQuery.toString());
        Page<User> page = Page.of(userQuery.getPageNo(), userQuery.getPageSize());
        if (StrUtil.isNotBlank(userQuery.getSortBy())) {
            page.addOrder(new OrderItem("update_time", false));
        } else {
            page.addOrder(new OrderItem(userQuery.getSortBy(), userQuery.getIsAsc()));
        }
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        Page<User> p = lambdaQuery().like(userQuery.getName() != null, User::getUsername, name).eq(status != null, User::getStatus, status).page(page);
        List<User> records = p.getRecords();
        PageDTO<UserVO> userVOPageDTO = new PageDTO<>();
        userVOPageDTO.setPages(p.getPages());
        userVOPageDTO.setTotal(p.getTotal());
        if (p.getRecords() == null) {
            userVOPageDTO.setList(Collections.emptyList());
            return userVOPageDTO;
        }
        userVOPageDTO.setList(BeanUtil.copyToList(p.getRecords(), UserVO.class));
        return userVOPageDTO;
    }
}
